package medical_application;
/** CSIS 343 Group 2 Course Project
 *  @authors Agnes Oliveira, Liane Heidemann, Daniel Schraufnagel, Matthew Lee
 */
import javax.swing.*;

import medical_application.Patient;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *  Class that generates the search GUI and data members with event handlers.
 */
public class SearchGUI extends JFrame{
	private static final long serialVersionUID = 1L;
	JButton selectRecord, searchButton;
	JMenuBar searchMenuBar;
	JMenu searchMenu;
	JMenuItem backupXMLMenuItem, createRecordMenuItem, exitMenuItem;
	static JList <Patient>searchList;
	JTextField firstName, lastName;
	
	public SearchGUI(){
		this.setSize(800, 425);
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.setResizable(false);
		this.setTitle("S E A R C H      R E C O R D S");
		
		JPanel searchPanel = new JPanel();
		searchPanel.setLayout(new GridBagLayout());
		JLabel fNameLabel = new JLabel("Patient First: ");
		fNameLabel.setFont(Main.f);
		addToPanel(searchPanel, fNameLabel, 0, 0, 1, 1, GridBagConstraints.EAST);
		
		searchMenuBar = new JMenuBar();
		searchMenu = new JMenu("Program");
		searchMenu.setFont(Main.f);
		backupXMLMenuItem = new JMenuItem("Save Patient Records");
		backupXMLMenuItem.setFont(Main.f);
		createRecordMenuItem = new JMenuItem("Create Patient Record");
		createRecordMenuItem.setFont(Main.f);
		exitMenuItem = new JMenuItem("Exit Program");
		exitMenuItem.setFont(Main.f);
		searchMenu.add(createRecordMenuItem);
		searchMenu.add(backupXMLMenuItem);
		searchMenu.add(exitMenuItem);
		searchMenuBar.add(searchMenu);
		this.setJMenuBar(searchMenuBar);
		
		firstName = new JTextField(30);
		firstName.setFont(Main.f);
		addToPanel(searchPanel, firstName, 1, 0, 3, 1, GridBagConstraints.WEST);
		
		JLabel required1Label = new JLabel("* Required");
		required1Label.setFont(Main.f);
		addToPanel(searchPanel, required1Label, 5, 0, 1, 1, GridBagConstraints.WEST);
		
		JLabel lNameLabel = new JLabel("Patient Last: ");
		lNameLabel.setFont(Main.f);
		addToPanel(searchPanel, lNameLabel, 0, 1, 1, 1, GridBagConstraints.EAST);
		
		lastName = new JTextField(30);
		lastName.setFont(Main.f);
		addToPanel(searchPanel, lastName, 1, 1, 3, 1, GridBagConstraints.WEST);
		
		JLabel required2Label = new JLabel("* Required");
		required2Label.setFont(Main.f);
		addToPanel(searchPanel, required2Label, 5, 1, 1, 1, GridBagConstraints.WEST);
		
		searchButton = new JButton("Search");
		searchButton.setFont(Main.f);
		addToPanel(searchPanel, searchButton, 5, 2, 1, 1, GridBagConstraints.NORTHWEST);
		
		JLabel resultLabel = new JLabel("Results: ");
		resultLabel.setFont(Main.f);
		addToPanel(searchPanel, resultLabel, 0, 3, 1, 1, GridBagConstraints.NORTHEAST);
		
		searchList = new JList<Patient>();
		searchList.setFont(new Font("Monospaced", Font.PLAIN, 20));
		searchList.setFixedCellHeight(20);
		searchList.setFixedCellWidth(365);
		searchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		JScrollPane searchScroll = new JScrollPane(searchList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		addToPanel(searchPanel, searchScroll, 1, 3, 3, 6, GridBagConstraints.NORTHWEST);
		
		selectRecord = new JButton("Select Record");
		selectRecord.setFont(Main.f);
		addToPanel(searchPanel, selectRecord, 5, 10, 1, 1, GridBagConstraints.SOUTH);
		
		actionCreateRecord();
		actionSelectRecord();
		actionSearchRecord();
		actionBackup();
		actionExit();
		this.add(searchPanel);
		this.setVisible(true);
		this.setLocationRelativeTo(null);
	}//end of constructor
	
	/** This method adds components to the JPanel using the GridBagLayout Manager and GridBag constraints **/
	private void addToPanel(JPanel p, JComponent c, int x, int y, int width, int height, int align){
		GridBagConstraints gc = new GridBagConstraints();
		gc.gridx = x;
		gc.gridy = y;
		gc.gridwidth = width;
		gc.gridheight = height;
		gc.weightx = 100.0;
		gc.weighty = 100.0;
		gc.insets = new Insets(2, 2, 2, 2);
		gc.anchor = align;
		gc.fill = GridBagConstraints.NONE;
		p.add(c, gc);
	}//end of addToPanel
	
	/**
	 * This method creates a blank patient record to be filled out.
	 */
	public void actionCreateRecord(){
		createRecordMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				firstName.setText(null);
				lastName.setText(null);
				searchList.clearSelection();
				new PatientGUI();
				}
		});
	}//end of actionCreateRecord
	
	/**
	 * This method removed the selected patient record from the JList / Patient vector.
	 */
	public void actionSelectRecord(){
		selectRecord.addActionListener(new ActionListener() {
			Patient temp;
			public void actionPerformed(ActionEvent ae) {
				if(!searchList.isSelectionEmpty()){
					try {
						Iterator<Patient> it = Read_Write_XML.patientVector.iterator();
						
						String delims = "[, ]";	
						String split[] = searchList.getSelectedValue().toString().split( delims );
						int index = 0;
						while( it.hasNext() ){
							Patient tempPatient = it.next();
							int compareFirst =  tempPatient.getFirst().compareTo( split[2] );
							int compareLast = tempPatient.getLast().compareTo( split[0] );
							
							if ( compareFirst == 0 && compareLast == 0 ){
								temp = Read_Write_XML.patientVector.remove( index );
								Intake.fName = temp.getFirst();
								Intake.lName = temp.getLast();
								new PatientGUI(temp);
								searchList.clearSelection();
							}
							index++;
						}
					} catch (ConcurrentModificationException e){
					}
				}	
				else 
					JOptionPane.showMessageDialog(null, "Select a record to display", "E R R O R", JOptionPane.ERROR_MESSAGE);
			}
		});
	}//end of actionSelectRecord
	
	/**
	 * This method searches the patient vector for first / last names.
	 * @return patient record(s) into the JList component
	 */
	public void actionSearchRecord(){
		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				boolean found = false;
				String searchFirst = firstName.getText().toUpperCase();
				String searchLast = lastName.getText().toUpperCase();
				
				Vector<Patient> results = new Vector<Patient>();
				Iterator<Patient> it = Read_Write_XML.patientVector.iterator();
					try{
						/* Let's loop through our patient vector and see if we have a match */
						while (it.hasNext()){
							Patient temp = it.next();
							String tempFirst = temp.getFirst(), tempLast = temp.getLast();
							
							if(searchLast.isEmpty() && !searchFirst.isEmpty()){
								if(searchFirst.charAt(0) == tempFirst.charAt(0) || searchFirst.toLowerCase().charAt(0) == tempFirst.charAt(0))
									found = true;
							}
							if(searchFirst.isEmpty() && !searchLast.isEmpty()){
								if(searchLast.charAt(0) == tempLast.charAt(0) || searchLast.toLowerCase().charAt(0) == tempLast.charAt(0))
									found = true;
							}
							if(!searchFirst.isEmpty() && !searchLast.isEmpty()){
								if((searchFirst.charAt(0) == tempFirst.charAt(0) && searchLast.charAt(0) == tempLast.charAt(0)) ||
										(searchFirst.toLowerCase().charAt(0) == tempFirst.charAt(0) && searchLast.toLowerCase().charAt(0) == tempLast.charAt(0))
										|| (searchFirst.charAt(0) == tempFirst.charAt(0) && searchLast.toLowerCase().charAt(0) == tempLast.charAt(0)) ||
										(searchFirst.toLowerCase().charAt(0) == tempFirst.charAt(0) && searchFirst.charAt(0) == tempLast.charAt(0)))
									found = true;
							}
							if(found)
								results.addElement(temp);
							found = false;
						}
						searchList.setListData(results);
						firstName.setText(null);
						lastName.setText(null);
						if (results.isEmpty())
							JOptionPane.showMessageDialog(null, "No record(s) found, try again", "N O   R E C O R D   F O U N D", JOptionPane.WARNING_MESSAGE);
					}catch(StringIndexOutOfBoundsException e){
						JOptionPane.showMessageDialog(null, "String Index Out of Bounds", "E R R O R", JOptionPane.ERROR_MESSAGE);
					}
			}
			
		});
	}//end of actionSearchRecord
	
	/**
	 * This method call the writePatientXML method which saves our patient record to an XML file.
	 */
	public void actionBackup(){
		backupXMLMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
					Main.rwxml.writePatientXML();
					JOptionPane.showMessageDialog(null, "Patient Records Saved", "D A T A     S A V E D", JOptionPane.INFORMATION_MESSAGE);
				}
		});
	}//end of actionBackup
	
	/** This method exits the program **/
	public void actionExit(){
		exitMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
					System.exit(0);
				}
		});
	}//end of actionExit
}//end of SearchGUI